package com.cqndt.disaster.device.service.impl;

import java.util.*;
import java.io.File;
import java.io.IOException;
import com.cqndt.disaster.device.vo.Monitor;
import com.github.pagehelper.util.StringUtil;
import org.springframework.stereotype.Service;
import com.cqndt.disaster.device.util.StringTool;
import com.cqndt.disaster.device.vo.AppTabDevice;
import com.cqndt.disaster.device.domain.TabAttachment;
import org.springframework.web.multipart.MultipartFile;
import com.cqndt.disaster.device.dao.AppTabProjectMapper;
import org.springframework.beans.factory.annotation.Value;
import com.cqndt.disaster.device.dao.AppTabStaticTypeMapper;
import com.cqndt.disaster.device.service.AppTabProjectService;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * Created By marc
 * Date: 2019/5/12  10:32
 * Description:
 */
@Service
public class AppTabProjectServiceImpl implements AppTabProjectService {

    @Autowired
    private AppTabProjectMapper appTabProjectMapper;

    @Value("${file-ip}")
    private String fileIp;
    @Autowired
    private AppTabStaticTypeMapper appTabStaticTypeMapper;

    @Value("${upload-path}")
    private String uploadPath;

    @Override
    public List<Map<String,Object>> selectByCondition(String userId, String level, String areaCode, String id, String search) {
        String areaCodeSplit = areaCode.substring(0,2);
        List<Map<String,Object>> list = appTabProjectMapper.selectByCondition(userId,level,areaCode,id,search,areaCodeSplit);
        for (Map<String,Object> map:list) {
            if(null != map.get("projectImg")&& !("").equals(map.get("projectImg"))){
                String photos = (String)map.get("projectImg");
                String[] ids = photos.split(",");
                List<Map<String,Object>> attachments = appTabProjectMapper.selectAttachmentIds(ids);
                List<String> listStr = new ArrayList<>();
                for (Map<String,Object> mapList:attachments) {
                    listStr.add((String)mapList.get("phUrl"));
                }
                map.put("photo",listStr);
            }else{
                map.put("photo",new ArrayList<>());
            }
        }
        return list;
    }

    @Override
    public Map<String, Object> selectByIdDetails(Integer projectId,String userId) {
        Map<String, Object> map = appTabProjectMapper.selectByIdDetails(projectId,userId);
        if(null != map.get("projectImg") && !("").equals(map.get("projectImg"))){
            String photos = (String)map.get("projectImg");
            String[] ids = photos.split(",");
            List<Map<String,Object>> attachments = appTabProjectMapper.selectAttachmentIds(ids);
            List<String> listStr = new ArrayList<>();
            for (Map<String,Object> mapList:attachments) {
                listStr.add((String)mapList.get("phUrl"));
            }
            map.put("photo",listStr);
        }else{
            map.put("photo",new ArrayList<>());
        }
        if(null != map.get("projectVideo") && !("").equals(map.get("projectVideo"))){
            String photos = (String)map.get("projectVideo");
            String[] ids = photos.split(",");
            List<Map<String,Object>> attachments = appTabProjectMapper.selectAttachmentIds(ids);
            List<String> listStr = new ArrayList<>();
            for (Map<String,Object> mapList:attachments) {
                listStr.add((String)mapList.get("phUrl"));
            }
            map.put("video",listStr);
        }else{
            map.put("video",new ArrayList<>());
        }
        return map;
    }

    @Override
    public List<Map<String, Object>> selectAllPush(String userId) {
        List<Map<String, Object>> list = appTabProjectMapper.selectAllPush(userId);
        for (Map<String,Object> map:list) {
            if(null != map.get("projectImg") && !("").equals(map.get("projectImg"))){
                String photos = (String)map.get("projectImg");
                String[] ids = photos.split(",");
                List<Map<String,Object>> attachments = appTabProjectMapper.selectAttachmentIds(ids);
                List<String> listStr = new ArrayList<>();
                for (Map<String,Object> mapList:attachments) {
                    listStr.add((String)mapList.get("phUrl"));
                }
                map.put("photo",listStr);
            }else{
                map.put("photo",new ArrayList<>());
            }
        }
        return list;
    }

    @Override
    public List<Map<String, Object>> selectProjectDatum(Integer projectId) {
        return appTabProjectMapper.selectProjectDatum(projectId);
    }

    @Override
    public Map<String, Object> getByProjectId(Integer projectId,String search, Integer monitorType) {
        Map<String, Object> map = new HashMap<>();
        List<Map<String,Object>> list = appTabStaticTypeMapper.selectByStaticNum("11");
        //离线时间判断
        Integer num = (Integer)list.get(0).get("id");
        List<Map<String, Object>> listData = appTabProjectMapper.getByProjectId(projectId,search,monitorType,num);
        Integer zxNum = appTabProjectMapper.countDeviceZxForProject(projectId,num,monitorType);
        Integer totalNum = listData.size();
        map.put("listData",listData);
        map.put("zxNum",zxNum);
        map.put("totalNum",totalNum);

        return map;
    }

    @Override
    public Monitor getMonitorDataById(Integer monitorId) {
        Monitor monitor = appTabProjectMapper.getMonitorDataById(monitorId);
        List<Map<String,Object>> list = appTabStaticTypeMapper.selectByStaticNum("11");
        //离线时间判断
        Integer num = (Integer)list.get(0).get("id");
        AppTabDevice device = appTabProjectMapper.selectDeviceById(monitor.getDeviceId(),num);
        monitor.setDevice(device);
        return monitor;
    }

    @Override
    public List<Map<String, Object>> selectAttachmentImgs(Integer projectId,String userId) {
        List<Map<String,Object>> attachments = new ArrayList<>();
        Map<String, Object> map = appTabProjectMapper.selectByIdDetails(projectId,userId);
        if(null != map.get("projectImg") && !("").equals(map.get("projectImg"))){
            String photos = (String)map.get("projectImg");
            String[] ids = photos.split(",");
            attachments = appTabProjectMapper.selectForProjectId(ids);
            for (Map<String,Object> mapList:attachments) {
                mapList.put("Url",fileIp+ "/img/"+mapList.get("Url"));
                mapList.put("projectId", projectId);
                mapList.put("type", "1");
            }
        }
        return attachments;
    }

    @Override
    public List<Map<String, Object>> selectAttachmentVideos(Integer projectId,String userId) {
        List<Map<String,Object>> attachments = new ArrayList<>();
        Map<String, Object> map = appTabProjectMapper.selectByIdDetails(projectId,userId);
        if(null != map.get("projectVideo") && !("").equals(map.get("projectVideo"))){
            String photos = (String)map.get("projectVideo");
            String[] ids = photos.split(",");
            attachments = appTabProjectMapper.selectForProjectId(ids);
            for (Map<String,Object> mapList:attachments) {
                mapList.put("Url",fileIp+"/video/"+mapList.get("Url"));
                mapList.put("projectId", projectId);
                mapList.put("type", "2");
            }
        }
        return attachments;
    }

    @Override
    public int uploadProjectImg(MultipartFile file, Integer projectId,String userId) {
        File  cfile = new File(uploadPath+File.separator+"img"+File.separator+"device"+File.separator);
        if (!cfile.exists()){
            cfile.mkdirs();
        }
        //获取图片名称
        String fileName = file.getOriginalFilename();
        //取出后缀
        String newFileName = "device/"+UUID.randomUUID()+fileName.substring(fileName.lastIndexOf("."));
        //存储图片
        try {
            file.transferTo(new File(uploadPath+File.separator+"img"+File.separator+newFileName));
            TabAttachment tabAttachment = new TabAttachment();
            tabAttachment.setAttachmentDate(new Date());
            tabAttachment.setAttachmentName(fileName);
            tabAttachment.setAttachmentUrl(newFileName);
            tabAttachment.setAttachmentDesc("项目图片");
            tabAttachment.setAttachmentType("1");
            appTabProjectMapper.insertTabAttachmentSelective(tabAttachment);

            Map<String, Object> projectMap = appTabProjectMapper.selectByIdDetails(projectId, userId);

            if(projectMap == null){
                return -1;
            }

            String projectImgs = projectMap.get("projectImg").toString();
            if(StringUtil.isEmpty(projectImgs)){
                projectImgs = String.valueOf(tabAttachment.getId());
            } else {
                projectImgs = projectImgs + "," + String.valueOf(tabAttachment.getId());
            }
            return appTabProjectMapper.updateProjectImgs(projectImgs, projectId);
        } catch (IOException e) {
            e.printStackTrace();
            return -1;
        }
    }

    @Override
    public int uploadProjectVideo(MultipartFile file, Integer projectId,String userId) {
        File  cfile = new File(uploadPath+File.separator+"video"+File.separator+"device"+File.separator);
        if (!cfile.exists()){
            cfile.mkdirs();
        }
        //获取图片名称
        String fileName = file.getOriginalFilename();
        //取出后缀
        String newFileName = "device/"+UUID.randomUUID()+fileName.substring(fileName.lastIndexOf("."));
        //存储图片
        try {
            file.transferTo(new File(uploadPath+File.separator+"video"+File.separator+newFileName));
            TabAttachment tabAttachment = new TabAttachment();
            tabAttachment.setAttachmentDate(new Date());
            tabAttachment.setAttachmentName(fileName);
            tabAttachment.setAttachmentUrl(newFileName);
            tabAttachment.setAttachmentDesc("项目视频");
            tabAttachment.setAttachmentType("2");
            appTabProjectMapper.insertTabAttachmentSelective(tabAttachment);

            Map<String, Object> projectMap = appTabProjectMapper.selectByIdDetails(projectId, userId);

            if(projectMap == null){
                return -1;
            }

            String projectVideos = projectMap.get("projectVideo").toString();
            if(StringUtil.isEmpty(projectVideos)){
                projectVideos = String.valueOf(tabAttachment.getId());
            } else {
                projectVideos = projectVideos + "," + String.valueOf(tabAttachment.getId());
            }
            return appTabProjectMapper.updateProjectVideos(projectVideos, projectId);
        } catch (IOException e) {
            e.printStackTrace();
            return -1;
        }
    }

    @Override
    public int deleteProjectOrVideo(Integer fileId, Integer projectId, String userId, Integer type) {

        Map<String, Object> projectMap = appTabProjectMapper.selectByIdDetails(projectId, userId);

        if(projectMap == null){
            return -1;
        }

        if(type == 1){ // 图片
            String projectImgs = projectMap.get("projectImg").toString();
            String[] imgs = projectImgs.split(",");
            List<String> imgList = new ArrayList<>();
            for(String img : imgs){
                if(Integer.parseInt(img) == (fileId)){
                    continue;
                }
                imgList.add(img);
            }
            return appTabProjectMapper.updateProjectImgs(StringTool.listToString(imgList, ","), projectId);
        } else {
            String projectVideos = projectMap.get("projectVideo").toString();
            String[] videos = projectVideos.split(",");
            List<String> videoList = new ArrayList<>();
            for(String video : videos){
                if(Integer.parseInt(video) == (fileId)){
                    continue;
                }
                videoList.add(video);
            }
            return appTabProjectMapper.updateProjectVideos(StringTool.listToString(videoList, ","), projectId);
        }
    }

}
